namespace VividKit.ServiceModel
{
	using System;
	using System.Diagnostics;
	using System.Threading.Tasks;

	public class TraceCommandDispatcher : ICommandDispatcher
	{
		private readonly ICommandDispatcher commandDispatcher;

		public TraceCommandDispatcher(ICommandDispatcher commandDispatcher)
		{
			this.commandDispatcher = commandDispatcher;
		}

		public async Task ExecuteAsync<TCommand>(TCommand command) where TCommand : class, ICommand
		{
			var stopwatch = new Stopwatch();
			try
			{
				Debug.WriteLine("Executing {0}", command.GetType().Name);

				stopwatch.Start();
				await this.commandDispatcher.ExecuteAsync(command);
			}
			catch (Exception x)
			{
				Debug.WriteLine(x.ToString());
				throw;
			}
			finally
			{
				stopwatch.Stop();
				Debug.WriteLine("Executed {0} ({1} ms)",
					command.GetType().Name, stopwatch.ElapsedMilliseconds);
			}
		}
	}
}